/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import static src.Generics.copyAll;

class Fruit {
}

class Apple extends Fruit implements Comparable<Apple> {

    Integer id = 0;
    
    Apple(Integer id) {
        this.id = id;
    }

    @Override
    public int compareTo(Apple o) {
        return id.compareTo(o.id);
    }
}

class RedApple extends Apple {
    
    RedApple(Integer id) {
        super(id);
    }
}

class Orange extends Fruit {
}

class Melon {
}

public class Generics {

    static <T> void fromArrayToCollection(T[] a, Collection<? super T> c) {
        for (T o : a) {
            c.add(o);
        }
    }

    static <T1 extends Fruit, T2 extends T1> void copyAll(Collection<T2> in, Collection<T1> out) {
        out.addAll(in);
    }
    
    static <T extends Fruit> Collection<T> getGreaters(Collection<T> in, T elem) {
        Collection<T> out = new ArrayList<>();
        for (Iterator<T> it = in.iterator(); it.hasNext(); ) {
            T x = it.next();
            Comparable<T> xx = (Comparable<T>) x;
            if (xx.compareTo(elem) > 0) {
                out.add(x);
            }
        }
        return out;
    }

    public static void main(String[] args) {
        Integer[] arr = {2,3,6,1,9,3};
        Collection<Number> cn = new ArrayList<>();
        fromArrayToCollection(arr, cn);
        for(Number n : cn) {
            System.out.print(n + " ");
        }
        System.out.println();
        
        List<Fruit> fr = new ArrayList<>();
        List<Apple> app = new ArrayList<>();
        List<Orange> or = new ArrayList<>();
        List<RedApple> rapp = new ArrayList<>();
        List<Melon> mel = new ArrayList<>();
        List<Object> ob = new ArrayList<>();
        
        or.add(new Orange());
        rapp.add(new RedApple(1));
        rapp.add(new RedApple(2));
        app.add(new Apple(3));
        app.add(new Apple(4));
        app.add(new Apple(5));

        copyAll(or, fr);
        copyAll(rapp, fr);
        copyAll(rapp, app);
        copyAll(rapp, rapp);
        System.out.println("or.size() = " + or.size());
        System.out.println("fr.size() = " + fr.size());
        System.out.println("app.size() = " + app.size());
        System.out.println("rapp.size() = " + rapp.size());
        
        Collection<Apple> app2 = getGreaters(app, new RedApple(2));
        System.out.println("app2.size() = " + app2.size());    
    }
}